package dao

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"yun_image/config/api"
	"yun_image/config/dataBase"
	"yun_image/entity"
	"yun_image/util"
)

var DB *gorm.DB

func initDB() {
	//配置MySQL连接参数
	username := dataBase.Username //账号
	password := dataBase.Password //密码
	host := dataBase.Host         //数据库地址，可以是Ip或者域名
	port := dataBase.Port         //数据库端口
	Dbname := dataBase.Dbname     //数据库名
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", username, password, host, port, Dbname)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic("连接数据库失败, error=" + err.Error())
	} else {
		fmt.Println(util.Green("数据库连接成功"))
	}
	DB = db
}

// 把权限信息写入数据库
func initApiAccess() error {
	result := DB.Exec("delete from `api_access`")
	if result.Error != nil {
		return result.Error
	}
	for path, roleIds := range api.ApiAccess {
		for _, roleId := range roleIds {
			var apiAccess = entity.ApiAccess{
				RoleId:  roleId,
				ApiPath: path,
			}
			result = DB.Create(&apiAccess)
			if result.Error != nil {
				return result.Error
			}
		}
	}
	return nil
}

// 在这里执行该包的所有初始化操作
func init() {
	initDB()
	initWeiboDB()
	err := pullAllRoles()
	if err != nil {
		fmt.Println("数据库初始化失败" + err.Error())
	}
	err = pullAllWebAccess()
	if err != nil {
		fmt.Println("数据库初始化失败" + err.Error())
	}
	err = initApiAccess()
	if err != nil {
		fmt.Println("apiAccess写入失败" + err.Error())
	}
	err = pullAllApiAccess()
	if err != nil {
		fmt.Println("apiAccess抓取失败" + err.Error())
	}

}
